<script setup lang="ts">
import { ref } from "vue";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useNotifyRecord } from "./utils/hook";

import Refresh from "~icons/ep/refresh";
import View from "~icons/ep/view";
import RefreshRight from "~icons/ep/refresh-right";
import Plus from "~icons/ep/plus";
defineOptions({ name: "NotifyRecord" });

const tableRef = ref();

const {
  filterForm,
  templates,
  channelOptions,
  statusOptions,
  pagination,
  tableData,
  columns,
  loading,
  detailVisible,
  detailLoading,
  detailRecord,
  detailSelection,
  openCreate,
  handleSearch,
  handleResetFilters,
  handlePageChange,
  handleSizeChange,
  openDetail,
  closeDetail,
  handleResend,
  handleResendSelected,
  handleResendSingle,
  handleDetailSelectionChange,
  channelLabel,
  statusLabel,
  statusTagType,
  uniqueChannels
} = useNotifyRecord();

const payloadText = (payload: Record<string, any> | undefined) => {
  if (!payload || Object.keys(payload).length === 0) {
    return "-";
  }
  try {
    return JSON.stringify(payload, null, 2);
  } catch (error) {
    return String(payload);
  }
};
</script>

<template>
  <div class="notify-record-page">
    <el-form
      :inline="true"
      :model="filterForm"
      class="search-form bg-bg_color w-full pl-4 pt-3 pb-2 overflow-auto"
    >
      <template #buttons>
        <el-button
          type="primary"
          :icon="useRenderIcon(Plus)"
          @click="openCreate"
        >
          添加消息
        </el-button>
      </template>
      <el-form-item label="关键字：" prop="keyword">
        <el-input
          v-model.trim="filterForm.keyword"
          placeholder="标题 / 模板 / 接收方"
          clearable
          class="w-[220px]!"
        />
      </el-form-item>
      <el-form-item label="模板：" prop="template_id">
        <el-select
          v-model="filterForm.template_id"
          placeholder="全部模板"
          clearable
          filterable
          class="w-[220px]!"
        >
          <el-option label="全部模板" value="" />
          <el-option
            v-for="item in templates"
            :key="item.id || item.type"
            :label="
              item.name ? `${item.name} (${item.type || '未标识'})` : item.type
            "
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="渠道：" prop="channel">
        <el-select
          v-model="filterForm.channel"
          placeholder="全部渠道"
          clearable
          filterable
          class="w-[160px]!"
        >
          <el-option label="全部渠道" value="" />
          <el-option
            v-for="item in channelOptions"
            :key="item"
            :label="channelLabel(item)"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态：" prop="status">
        <el-select
          v-model="filterForm.status"
          placeholder="全部状态"
          clearable
          class="w-[140px]!"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="日期：" prop="dateRange">
        <el-date-picker
          v-model="filterForm.dateRange"
          type="daterange"
          range-separator="到"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          unlink-panels
          class="w-[280px]!"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="handleSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="handleResetFilters">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar
      title="发送记录"
      :columns="columns"
      :tableRef="tableRef"
      @refresh="handleSearch"
      @fullscreen="tableRef.value?.setAdaptive?.()"
    >
      <template #buttons>
        <el-button
          type="primary"
          :icon="useRenderIcon(Plus)"
          @click="openCreate"
        >
          添加消息
        </el-button>
      </template>
      <template #default="{ size, dynamicColumns }">
        <PureTable
          ref="tableRef"
          v-loading="loading"
          row-key="id"
          :columns="dynamicColumns"
          :data="tableData"
          :size="size"
          :pagination="pagination"
          adaptive
          :adaptiveConfig="{ offsetBottom: 48 }"
          @page-current-change="handlePageChange"
          @page-size-change="handleSizeChange"
        >
          <template #template="{ row }">
            <div class="template-cell">
              <span class="template-cell__name">
                {{ row.template_name || "-" }}
              </span>
              <el-tag
                v-if="row.template_type"
                size="small"
                effect="plain"
                class="template-cell__tag"
              >
                {{ row.template_type }}
              </el-tag>
            </div>
          </template>
          <template #channels="{ row }">
            <template v-if="row.recipients && row.recipients.length">
              <el-space wrap :size="6">
                <el-tag
                  v-for="channel in uniqueChannels(row.recipients)"
                  :key="channel"
                  size="small"
                  effect="plain"
                >
                  {{ channelLabel(channel) }}
                </el-tag>
              </el-space>
            </template>
            <span v-else>-</span>
          </template>
          <template #status="{ row }">
            <el-tag
              :type="statusTagType(row.status)"
              size="small"
              effect="plain"
            >
              {{ statusLabel(row.status, row.status_text) }}
            </el-tag>
          </template>
          <template #operation="{ row, size }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :icon="useRenderIcon(View)"
              :size="size"
              @click="openDetail(row)"
            >
              详情
            </el-button>
            <el-button
              class="reset-margin"
              link
              type="warning"
              :icon="useRenderIcon(RefreshRight)"
              :size="size"
              @click="handleResend(row)"
            >
              重推
            </el-button>
          </template>
        </PureTable>
      </template>
    </PureTableBar>

    <el-drawer
      v-model="detailVisible"
      :title="
        detailRecord?.title ? `通知详情 - ${detailRecord.title}` : '通知详情'
      "
      size="640px"
      append-to-body
      destroy-on-close
      :close-on-press-escape="true"
      :close-on-click-modal="false"
    >
      <div v-loading="detailLoading" class="detail-wrapper">
        <template v-if="detailRecord">
          <el-descriptions :column="1" border class="detail-descriptions">
            <el-descriptions-item label="消息标题">
              {{ detailRecord.title || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="模板">
              <span>{{ detailRecord.template_name || "-" }}</span>
              <el-tag
                v-if="detailRecord.template_type"
                size="small"
                effect="plain"
                class="detail-tag"
              >
                {{ detailRecord.template_type }}
              </el-tag>
              <el-tag
                v-if="detailRecord.category"
                size="small"
                type="info"
                effect="plain"
                class="detail-tag"
              >
                {{ detailRecord.category }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag
                :type="statusTagType(detailRecord.status)"
                size="small"
                effect="plain"
              >
                {{ statusLabel(detailRecord.status, detailRecord.status_text) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="发送时间">
              {{ detailRecord.sent_at || "未发送" }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ detailRecord.create_time || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="通知内容">
              <div class="detail-content">
                {{ detailRecord.content || "-" }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="附加数据">
              <pre class="payload-block"
                >{{ payloadText(detailRecord.payload) }}
              </pre>
            </el-descriptions-item>
          </el-descriptions>

          <el-card class="detail-card" shadow="never">
            <template #header>
              <div class="detail-card__header">
                <div>
                  <span>接收人列表</span>
                  <el-tag
                    v-if="detailRecord.recipients?.length"
                    class="detail-count"
                    size="small"
                    effect="plain"
                    type="info"
                  >
                    共 {{ detailRecord.recipients.length }} 人
                  </el-tag>
                </div>
                <div class="detail-card__actions">
                  <el-button
                    type="primary"
                    size="small"
                    plain
                    :disabled="detailSelection.length === 0"
                    :icon="useRenderIcon(RefreshRight)"
                    @click="handleResendSelected"
                  >
                    批量重推
                  </el-button>
                </div>
              </div>
            </template>
            <el-table
              v-if="detailRecord.recipients?.length"
              :data="detailRecord.recipients"
              border
              stripe
              size="small"
              @selection-change="handleDetailSelectionChange"
            >
              <el-table-column type="selection" width="48" />
              <el-table-column label="接收方" min-width="150">
                <template #default="{ row }">
                  <div class="recipient-cell">
                    <el-tag size="small" effect="plain">
                      {{ row.target_type || "-" }}
                    </el-tag>
                    <span>{{ row.target_id || "-" }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="渠道" width="120">
                <template #default="{ row }">
                  <el-tag size="small" effect="plain">
                    {{ channelLabel(row.channel) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="状态" width="120">
                <template #default="{ row }">
                  <el-tag
                    :type="statusTagType(row.status)"
                    size="small"
                    effect="plain"
                  >
                    {{ statusLabel(row.status, row.status_text) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column
                prop="send_attempts"
                label="尝试次数"
                width="100"
              />
              <el-table-column prop="sent_at" label="发送时间" width="180" />
              <el-table-column prop="read_time" label="阅读时间" width="180" />
              <el-table-column label="操作" width="120">
                <template #default="{ row }">
                  <el-button
                    link
                    type="primary"
                    size="small"
                    :icon="useRenderIcon(RefreshRight)"
                    @click="handleResendSingle(row)"
                  >
                    重推
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-else :image-size="120" description="暂无接收人记录" />
          </el-card>
        </template>
        <template v-else>
          <el-empty description="未找到通知详情" />
        </template>
      </div>
      <template #footer>
        <div class="drawer-footer">
          <el-button type="primary" @click="closeDetail">关闭</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style scoped>
.notify-record-page {
  padding: 12px 12px 20px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 12px;
}

.template-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.template-cell__tag {
  margin-left: 4px;
}

.detail-wrapper {
  min-height: 200px;
}

.detail-descriptions {
  margin-bottom: 16px;
}

.detail-tag {
  margin-left: 8px;
}

.detail-content {
  white-space: pre-wrap;
  line-height: 1.5;
}

.payload-block {
  margin: 0;
  padding: 12px;
  background: var(--el-fill-color-light);
  border-radius: 6px;
  font-size: 12px;
  line-height: 1.5;
  word-break: break-all;
}

.detail-card {
  margin-top: 12px;
}

.detail-card__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.detail-card__actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.detail-count {
  margin-left: 8px;
}

.recipient-cell {
  display: flex;
  align-items: center;
  gap: 6px;
}

.drawer-footer {
  text-align: right;
}
</style>
